import json
import os
from group_by_page import group_by_page_id


def get_file_path(folder_path):
    """得到指定的文件路径"""
    for root, dirs, files in os.walk(folder_path):
        folder_name = os.path.basename(os.path.normpath(root))
        # 遍历指定目录的所有文件
        for file in files:
            # 筛选JSON文件
            if file.endswith('.json'):
                # 拼接文件的完整路径
                file_path = os.path.join(root, file)
                print(f'找到JSON文件:{file_path}')
                return file_path, folder_name


def get_db_folder(file_path):
    """读取指定文件"""
    # 读取指定路径的json文件
    with open(file=file_path, mode='r', encoding='utf-8') as file:
        # 将内容解析成json格式-->字典
        json_data = json.load(file)
        return json_data


def get_data_json(folder_path):
    """对获得的数据进行指定处理"""
    file_path, folder_name = get_file_path(folder_path)
    json_data = get_db_folder(file_path)

    # 获取书的基础信息
    book_info = json_data[0]

    # 如果不存在，则用文件夹名字
    title = folder_name if book_info.get('title', '').strip() == '' else book_info['title']

    # 拼接成指定的格式:为分页做准备
    pages_word = []
    for item in json_data:
        item = {
            'annotation_id': item['annotation_id'],
            'page_id': item['page_id'],
            'page_image_path': item['page_image_path'],
            'word': item['word'],
            'word_image_path': item['word_image_path'],
            'recognition_rate': item['recognition_rate'],
            'word_coordinates': item['word_coordinates']
        }
        pages_word.append(item)

    # 根据page_id分组
    pages_content_list = group_by_page_id(results=pages_word)

    # 返回以page_id为一个索引的列表，方便后面用for就可以直接以page_id为单位排序
    data = []
    for page_content in pages_content_list:
        # 设置基础信息
        item = {
            'book_id': book_info['book_id'],
            'title': book_info.get('title', title),
            'author': book_info.get('author', ''),
            'page_id': page_content['page_id'],
            'layout_direction': book_info['layout_direction'],
            'reading_sequence': book_info['reading_sequence'],
            'page_image_path': page_content['page_image_path'],
            'page_word': page_content['word_info'],
        }
        data.append(item)

    return data
